package vashion.azeroth.api.core.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import vashion.azeroth.back.core.context.BackUserContext;
import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.core.personal.pojo.PersonalMember;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 后台登陆校验
 */
public class BackLoginFilter implements Filter {

    private final static Logger log = LoggerFactory.getLogger(BackLoginFilter.class);
    @Autowired
    private BackUserContext userContext;

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if (req.getRequestURI().equals("/azeroth/back/login/login.htm")) {
            chain.doFilter(req, res);
        } else {

            PersonalMember loginUser = (PersonalMember) req.getSession().getAttribute(BackUserContext.LOGIN_USER);
            if (null == loginUser) {
                //返回登陆异常的错误,不能直接页面跳转
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().print("{\"errorCode\":" + CommonErrorEnum.NOT_LOGIN.getErrorCode() + ",\"errorMsg\":\"" + CommonErrorEnum.NOT_LOGIN.getErrorMessage() + "\",\"success\":false}");
                response.getWriter().flush();
            } else {
                chain.doFilter(req, res);
            }
        }
    }
}
